<?php


namespace apps\marriage\app\mp\controller;


use apps\marriage\core\logic\WeixinMpLogic;
use apps\marriage\core\service\SiteConfigService;

class IndexController extends BaseMarriageMpController
{
    /**
     * @var SiteConfigService
     */
    private $siteConfigService;

    /**
     * @var WeixinMpLogic
     */
    private $weixinMpLogic;

    const QRCODE_TICKET_CACHE_PREFIX = 'wechat_qrcode_ticket:';

    protected function init()
    {
        parent::init();
        $this->siteConfigService = service('SiteConfig', SERVICE_NAMESPACE);
        $this->weixinMpLogic = logic('WeixinMp', LOGIC_NAMESPACE);
    }

    public function site_config()
    {
        $sceneId = 1000;
        $ticket = cache(self::QRCODE_TICKET_CACHE_PREFIX . $sceneId);
        if(empty($ticket)) {
            $result = $this->weixinMpLogic->getApiClient()->create_qrcode($sceneId);
            if($result[1]) {
                $ticket = $result[1]->ticket;
                $expire_seconds = 2592000;
                cache(self::QRCODE_TICKET_CACHE_PREFIX . $sceneId, $ticket, $expire_seconds);
            }
        }
        if($ticket) {
            $qrcode = $this->weixinMpLogic->getApiClient()->get_qrcode_url($ticket);
        } else {
            $qrcode = null;
        }

        $prices = $this->siteConfigService->getValueByCode('prices');
        foreach ($prices as $key => &$val) {
            $val = floatval($val);
        }

        $matchmaker_salary_ratio = $this->siteConfigService->getValueByCode('matchmaker_salary_ratio');
        foreach ($matchmaker_salary_ratio as $key => &$val) {
            $val = floatval($val);
        }

        return $this->success([
            'cfg' => [
                'prices' => $prices,
                'matchmaker_salary_ratio' => $matchmaker_salary_ratio,
                'withdraw_cash_min_amount' => floatval($this->siteConfigService->getValueByCode('withdraw_cash_min_amount')),
                'mp_qrcode' => $qrcode,
                'wechat_subscribe_msg_enbale' => intval($this->siteConfigService->getValueByCode('wechat_subscribe_msg_enbale')),
                'subscribe_template' => config('subscribe_template'),
                'weixin_mp_app_id' => $this->siteConfigService->getValueByCode('weixin_mp_app_id'),
            ]
        ]);
    }
}